package com.hightemperator.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.UUID;

/**
 * 上传文件
 * 
 * @author MengJinyue
 * 
 */
public class UploadUtil {
	static Log log = LogFactory.getLog(UploadUtil.class);

	/**
	 * 根据图片路径下载图片
	 * @param request
	 * @param _url
	 * @return
	 * @throws Exception
	 */
	public static String download(HttpServletRequest request, String _url)
			throws Exception {
		String trueFileName = null;
		log.debug("上传文件开始, 地址: " + _url);
		try {
			URL url = new URL(_url);
			URLConnection con = url.openConnection();
			InputStream is = con.getInputStream();

			byte[] bs = new byte[1024];
			int len;
			String s = request.getSession().getServletContext().getRealPath("/");// 项目所在磁盘路径
			String projectName = request.getContextPath().replaceAll("/", "");
			s = s.substring(0, s.indexOf(projectName));// 去掉项目名
			trueFileName = "/pictures/au_avatar/" + UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
			String path = s + trueFileName;
			File sf = new File(path);
			log.debug("文件输出路径: " + path);
			OutputStream os = new FileOutputStream(sf);
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			// 完毕，关闭所有链接
			os.close();
			is.close();

		} catch (IOException e) {

		}
		return trueFileName;
	}
	public static String uploadFileToPath(MultipartFile[] file, String basePath , String path) {

		try {
			StringBuilder stringBuilder = new StringBuilder();
			basePath = basePath + Constant.SPEADER + path + Constant.SPEADER + new Date().getMonth();
			if(!new File(basePath).exists()){
				new File(basePath).mkdirs();
			}
			for(int i = 0; i < file.length; i ++){
				String fileName = file[i].getOriginalFilename();// 文件原名称

				// 判断文件类型
				String trueFileName = CommonUtil.getSimpleDate() + "-" +UUID.randomUUID().toString()
						.replaceAll("-", "").substring(10)
						+ fileName.substring(fileName.lastIndexOf(".")).toLowerCase();

				trueFileName = basePath + Constant.SPEADER+ trueFileName;
				log.debug("上传文件: " + trueFileName);
				File files = new File(trueFileName);
				try {
					file[i].transferTo(files);
				} catch (Exception e) {
					log.debug("文件上传异常" + e.getMessage());
					e.printStackTrace();
				}
				trueFileName = trueFileName.replaceAll("\\\\", "/");
				int pachNum = trueFileName.lastIndexOf(path);
				log.debug("返回文件名: " + trueFileName.substring(pachNum, trueFileName.length()));
				if( i == 0){
					stringBuilder.append(trueFileName.substring(trueFileName.lastIndexOf(path), trueFileName.length()));
				} else {
					stringBuilder.append("," + trueFileName.substring(trueFileName.lastIndexOf(path), trueFileName.length()));
				}
			}
			return stringBuilder.toString();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return "";
		}
	}

	public static String uploadVideoFile(HttpServletRequest request,MultipartFile file) {
		if (file != null) {
			String basePath = request.getSession().getServletContext().getRealPath("/");
	        String contextPath = request.getContextPath();
	        String tempStr = contextPath.substring(1, contextPath.length() );
	        basePath = basePath.substring(0, basePath.lastIndexOf(tempStr) );
	        String path = Constant.VIDEO_INDEX;
			try {
				basePath = basePath + Constant.SPEADER + path + Constant.SPEADER + new Date().getMonth();
				if(!new File(basePath).exists()){
					new File(basePath).mkdirs();
				}
				String fileName = file.getOriginalFilename();// 文件原名称

				// 判断文件类型
				String trueFileName = CommonUtil.getSimpleDate() + "-" +UUID.randomUUID().toString()
						.replaceAll("-", "").substring(10)
						+ fileName.substring(fileName.lastIndexOf(".")).toLowerCase();

				trueFileName = basePath + Constant.SPEADER+ trueFileName;
				log.debug("上传文件: " + trueFileName);
				File files = new File(trueFileName );
				try {
					file.transferTo(files);
				} catch (Exception e) {
					log.debug("文件上传异常" + e.getMessage());
					e.printStackTrace();
				}
				return trueFileName;
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		}
		return "";
		
	}
}
